package com.miaosha.controller;

import com.alibaba.druid.util.StringUtils;
import com.miaosha.controller.vo.UserVo;
import com.miaosha.error.BusinessException;
import com.miaosha.error.EmBusinessError;
import com.miaosha.response.CommonResultType;
import com.miaosha.service.UserService;
import com.miaosha.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * @Author: lxj
 * @Date: 2021.03.16 15:55
 * @version: 1.0
 */
@Controller
@RequestMapping("user")
//处理跨域请求问题，但对ajax、session无法做到跨域的共享
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*", originPatterns = "*")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * 用户登录
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResultType login(@RequestParam(name = "telphone") String telphone,
                                  @RequestParam(name = "password") String password) throws NoSuchAlgorithmException, BusinessException {

        //入参校验
        if(StringUtils.isEmpty(telphone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        //用户登录服务，校验用户登录合法性
        UserModel userModel = userService.validateLogin(telphone, this.EncodeByMD5(password));

        //将登录凭证加入到用户登录成功的session内（后面更改为使用分布式的session会话机制，这里假设用户单点登录）
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER", userModel);

        return CommonResultType.create(null);
    }

    /**
     * 用户注册
     *
     * @param telphone
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResultType register(@RequestParam(name = "telphone") String telphone,
                                     @RequestParam(name = "otpCode") String otpCode,
                                     @RequestParam(name = "name") String name,
                                     @RequestParam(name = "age") Integer age,
                                     @RequestParam(name = "gender") Byte gender,
                                     @RequestParam(name = "password") String password) throws NoSuchAlgorithmException, BusinessException {
        //验证手机号与对应otpCode符合
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);
        if (!StringUtils.equals(otpCode, inSessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符合");
        }
        //若符合，进入注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setAge(age);
        userModel.setGender(gender);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(this.EncodeByMD5(password));

        userService.register(userModel);
        return CommonResultType.create(null);
    }

    /**
     * 用户获取otp短信端口
     *
     * @param telphone
     * @return
     */
    @RequestMapping(value = "/getotp", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResultType getOtp(@RequestParam(name = "telphone") String telphone) {
        //按照一定规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000; //随便加一个
        String otpCode = String.valueOf(randomInt);

        //将OTP验证码与用户手机号关联(这里在分布式中用到redis)
        //这里使用httpSession的方式绑定
        httpServletRequest.getSession().setAttribute(telphone, otpCode);

        //将OTP验证码通过短信发送给用户（省略）

        System.out.println("telphone = " + telphone + " & otpCode = " + otpCode);

        return CommonResultType.create(null);
    }


    @RequestMapping("/get")
    @ResponseBody
    public CommonResultType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
        UserModel userModel = userService.getUserById(id);
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
//            userModel.setEncrptPassword("123");
        }
        UserVo userVo = convertFromModel(userModel);
        return CommonResultType.create(userVo);
    }

    private UserVo convertFromModel(UserModel userModel) {
        if (userModel == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userModel, userVo);
        return userVo;
    }


}
